package com.totoro.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.totoro.domain.School;
import com.totoro.service.SchoolService;
import com.totoro.util.CommonConstant;
import com.totoro.util.Page;

@Controller
@RequestMapping("/school")
public class SchoolController {

	@Autowired
	private SchoolService schoolService;

	@RequestMapping("/list")
	public ModelAndView list(Integer pageNo) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/school/list");
		pageNo = pageNo == null ? 1 : pageNo;
		Page<School> pagedPost = schoolService.getPagePosts(pageNo,
				CommonConstant.PAGE_SIZE);
		mav.addObject("pagedPost", pagedPost);
		mav.addObject("schoolList", pagedPost.getResult());
		mav.addObject("pageNo", pageNo);
		return mav;
	}

	@RequestMapping("/findByName")
	public ModelAndView findSchoolByName(String description) {
		System.out.println("description: " + description);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/school/list");
		mav.addObject("schoolList",
				schoolService.list("description", new String(description)));
		return mav;
	}

	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public String toSave() {
		return "/school/save";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(School school) {
		schoolService.save(school);
		return "redirect:/school/list.html";
	}

	@RequestMapping("/findById/{id}")
	public ModelAndView findById(@PathVariable("id") Integer id, Integer pageNo) {
		System.out.println("pageNo = " + pageNo);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/school/update");
		mav.addObject("school", schoolService.get(id));
		mav.addObject("pageNo", pageNo);
		return mav;
	}

	@RequestMapping("/update/{pageNo}")
	public String update(School school, @PathVariable("pageNo") Integer pageNo) {
		schoolService.update(school);
		return "redirect:/school/list.html?pageNo=" + pageNo;
	}

	@RequestMapping("/delete/{id}")
	public String delete(School school, Integer pageNo) {
		schoolService.deleteObject(school);
		return "redirect:/school/list.html?pageNo=" + pageNo;
	}
}
